<script>

    layui.use(['admin', 'form', 'upload'], function () {
        var $ = layui.$
            , form = layui.form
            , admin = layui.admin
            , upload = layui.upload;
        // 动态获取角色信息
        $(function () {

            admin.req({
                // url: 'http://10.0.23.97:8195/portal/gw/gwlist' //实际使用请改成服务端真实接口
                url: layui.setter.hostAddr + '/portal/gw/gwlist' //实际使用请改成服务端真实接口
                // ,type:'post'
                , dataType: 'json'
                , done: function (res) {
                    var post_lis = []
                    if (res.code == 0) {
                        for (var i = 0; i < res.data.length; i++) {
                            post_lis.push(res.data[i])
                        }
                        form.render();

                    }
                    layui.data('test', {
                        key: 'posts'
                        , value: post_lis
                    });
                }
            });
            admin.req({
                // url: 'http://10.0.23.97:8195/portal/role/rolelist' //实际使用请改成服务端真实接口
                url: layui.setter.hostAddr + '/portal/role/rolelist' //实际使用请改成服务端真实接口
                // ,type:'post'
                , dataType: 'json'
                , done: function (res) {
                    var role_lis = []
                    if (res.code == 0) {
                        for (var i = 0; i < res.data.length; i++) {
                            role_lis.push(res.data[i])
                        }
                        form.render();

                    }
                    layui.data('test', {
                        key: 'roles'
                        , value: role_lis
                    });
                }
            });

        })

    })

</script>
<title>用户管理</title>

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <div style="padding-bottom: 10px;">
                <button class="layui-btn layuiadmin-btn-useradmin mybtn" data-type="batchdel">删除</button>
                <button class="layui-btn layuiadmin-btn-useradmin mybtn" data-type="add">添加</button>
                <button class="layui-btn layuiadmin-btn-useradmin mybtn" lay-filter="LAY-user-front-search"
                        data-type="search"
                        style="float: right;margin: 0">
                    <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                </button>
                <input style="width: 200px; float: right" type="text"
                       name="userinfo"
                       value="" placeholder="请输入要查询的用户名称" autocomplete="off" class="layui-form layui-input">
                <!--                <datalist id="userinfo">-->
                <!--                </datalist>-->
            </div>

            <table id="LAY-user-manage" lay-filter="LAY-user-manage"></table>
            <script type="text/html" id="imgTpl">
                <img style="display: inline-block; width: 50%; height: 100%;" src={{ d.avatar }}>
            </script>
            <script type="text/html" id="table-useradmin-webuser">
                <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i
                        class="layui-icon layui-icon-edit"></i>编辑</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i
                        class="layui-icon layui-icon-delete"></i>删除</a>
                <a class="layui-btn layui-btn-warm layui-btn-xs"
                   lay-event="reset"><i
                        class="layui-icon layui-icon-refresh"></i>重置密码</a>
            </script>
            <script type="text/html" id="table-useradmin-webuser1">
                <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i
                        class="layui-icon layui-icon-edit"></i>编辑</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i
                        class="layui-icon layui-icon-delete"></i>删除</a>
            </script>

        </div>
    </div>
</div>

<script>
    var userwidth = 250;
    var operateId = '#table-useradmin-webuser';
    var currentUserRoles = window.currentUserMsg.roleNames
    if (currentUserRoles.indexOf('admin') === -1) {
        operateId = '#table-useradmin-webuser1'
        userwidth = 150;
    }

    layui.use(['table', 'form', 'admin'], function () {
        debugger

        var $ = layui.$
            , admin = layui.admin
            , view = layui.view
            , table = layui.table
            , form = layui.form
            , userInfo = $("input[name='userinfo']").val()
            , userdata
        table.set({
            headers: { //通过 request 头传递
                Authorization: layui.data('layuiAdmin').Authorization
            }
        });

        // $.ajax({
        //     url: "http://10.0.23.97:8195/portal/user/userlist",
        //     dataType: "json",
        //     async: false,
        //     beforeSend: function (XMLHttpRequest) {
        //         XMLHttpRequest.setRequestHeader("Authorization", layui.data('layuiAdmin').Authorization);
        //     },
        //     type: 'GET',
        //     success: function (res) {
        //         // debugger
        //         // for (let i = 0; i < res.data.length; i++) {
        //         //     var strRoles = ''
        //         //     if (res.data[i].haveGW != null && res.data[i].haveRoleList.length > 0) {
        //         //         console.log(666)
        //         //         res.data[i].haveGW = res.data[i].haveGW.GWMC
        //         //
        //         //         for (let j = 0; j < res.data[i].haveRoleList.length; j++) {
        //         //             if (j == res.data[i].haveRoleList.length - 1) {
        //         //                 strRoles += res.data[i].haveRoleList[j].roleName
        //         //             } else {
        //         //                 strRoles += res.data[i].haveRoleList[j].roleName + ','
        //         //             }
        //         //
        //         //         }
        //         //         res.data[i].haveRoleList = strRoles
        //         //     }
        //         // }
        //         console.log(JSON.stringify(res))
        //         userdata = res
        //         // doSuccess()
        //     },
        //     error: function (XMLHttpRequest, textStatus, errorThrown) {
        //         //通常情况下textStatus和errorThrown只有其中一个包含信息
        //         console.log(textStatus);   //调用本次ajax请求时传递的options参数
        //         console.log(errorThrown);   //调用本次ajax请求时传递的options参数
        //         doFail()
        //     }
        // })

        // 渲染用户信息
        table.render({
            elem: '#LAY-user-manage'
            // id:"usertable",
            // , data: userdata.data
            // ,url:"http://10.0.23.97:8195/portal/user/userlist"
            , url: layui.setter.hostAddr + "/portal/user/userlist"
            , cols: [[
                {type: 'checkbox', fixed: 'left'}
                , {field: 'userId', width: 100, title: '税务人员代码', sort: true}
                , {field: 'userName', title: '税务人员名称', minWidth: 100}
                // , {field: 'password', title: '密码', minWidth: 100}
                // ,{field: 'avatar', title: '角色', width: 100, templet: '#imgTpl'}
                , {field: 'roleNames', title: '角色名称'}
                , {field: 'gwName', title: '岗位名称'}
                , {field: 'phone', title: '手机号码'}
                , {field: 'email', title: '邮箱地址'}
                , {field: 'desc', title: '描述信息'}
                , {title: '操作', width: userwidth, align: 'center', fixed: 'right', toolbar: operateId}
            ]]
            , page: true
            , limit: 10
            , height: 'full-320'
            , text: '对不起，加载出现异常！'
        });

        // 监听工具条
        table.on('tool(LAY-user-manage)', function (obj) {
            var wholedata = obj.data, delobj = [];
            delobj.push(wholedata.userId)
            if (obj.event === 'del') {
                layer.prompt({
                    formType: 1
                    , title: '敏感操作，请验证口令'
                }, function (value, index) {
                    var del_data = {id: index, passcode: value}
                    console.log(del_data)
                    layer.close(index);

                    layer.confirm('真的删除行么', function (index) {
                        $.ajax({
                            url: layui.setter.hostAddr + `/portal/user/user`,
                            dataType: 'json',
                            data: JSON.stringify(delobj),
                            async: false,
                            beforeSend: function (XMLHttpRequest) {
                                XMLHttpRequest.setRequestHeader("Authorization", layui.data('layuiAdmin').Authorization);
                                XMLHttpRequest.setRequestHeader("Content-Type", "application/json");
                            },
                            type: 'DELETE',
                            success: function (res) {
                                doSuccess()
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                //通常情况下textStatus和errorThrown只有其中一个包含信息
                                console.log(textStatus);   //调用本次ajax请求时传递的options参数
                                console.log(errorThrown);   //调用本次ajax请求时传递的options参数
                                doFail()
                            }

                        })
                        obj.del();
                        layui.table.reload('LAY-user-manage');
                        layer.close(index);
                    });
                });
            } else if (obj.event === 'edit') {
                admin.popup({
                    title: '编辑用户'
                    , area: ['700px', '600px']
                    , id: 'LAY-popup-user-add'
                    , success: function (layero, index) {
                        view(this.id).render('user/user/userform', wholedata).done(function () {
                            // view(this.id).render('user/user/userform', data).done(function(){
                            form.render(null, 'layuiadmin-form-useradmin');

                            //监听提交
                            form.on('submit(LAY-user-front-submit)', function (data) {
                                var editfield = data.field; //获取提交的字段
                                debugger
                                var editUserField = {"userId": wholedata.userId, "roleIds": []}
                                for (var item in editfield) {
                                    if (editfield[item] == 'on') {
                                        editUserField['roleIds'].push(item)
                                    } else {
                                        editUserField[item] = editfield[item]
                                    }
                                }
                                editUserField['password'] = null
                                console.log("编辑后的信息===" + JSON.stringify(editUserField))
                                $.ajax({
                                    url: layui.setter.hostAddr + "/portal/user/user",
                                    dataType: "json",
                                    contentType: "application/json",
                                    data: JSON.stringify(editUserField),
                                    async: false,
                                    beforeSend: function (XMLHttpRequest) {
                                        XMLHttpRequest.setRequestHeader("Authorization", layui.data('layuiAdmin').Authorization);
                                    },
                                    type: 'PUT',
                                    success: function (res) {
                                        doSuccess()
                                    },
                                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                                        //通常情况下textStatus和errorThrown只有其中一个包含信息
                                        console.log(textStatus);   //调用本次ajax请求时传递的options参数
                                        console.log(errorThrown);   //调用本次ajax请求时传递的options参数
                                        doFail()
                                    }
                                })
                                layui.table.reload('LAY-user-manage'); //重载表格
                                layer.close(index); //执行关闭
                            });
                        });
                    }
                });
            } else if (obj.event === 'reset') {
                layer.prompt({
                    formType: 1
                    , title: '敏感操作，请验证口令'
                }, function (value, index) {
                    layer.close(index);
                    var userId = obj.data.userId
                    console.log(userId)

                    layer.confirm('确定重置该用户的密码吗？', function (index) {
                        $.ajax({
                            url: layui.setter.hostAddr + `/portal/user/resetpassword?userId=${userId}`,
                            dataType: 'json',
                            data: JSON.stringify(userInfo),
                            async: false,
                            beforeSend: function (XMLHttpRequest) {
                                XMLHttpRequest.setRequestHeader("Authorization", layui.data('layuiAdmin').Authorization);
                                XMLHttpRequest.setRequestHeader("Content-Type", "application/json");

                            },
                            type: 'GET',
                            success: function (res) {
                                // console.log("删除结果====" + JSON.stringify(res))
                                doSuccess()
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                //通常情况下textStatus和errorThrown只有其中一个包含信息
                                console.log(textStatus);   //调用本次ajax请求时传递的options参数
                                console.log(errorThrown);   //调用本次ajax请求时传递的options参数
                                doFail()
                            }

                        })
                        table.reload('LAY-user-manage');
                        layer.msg('密码已重置');
                    });
                });
            }
        });

        var active = {
            batchdel: function () {
                var checkStatus = table.checkStatus('LAY-user-manage')
                    , checkData = checkStatus.data, delobjs = []; //得到选中的数据

                if (checkData.length === 0) {
                    return layer.msg('请选择数据');
                }
                for (let i = 0; i < checkData.length; i++) {
                    delobjs.push(checkData[i].userId)
                }
                console.log("要删除的数据====" + JSON.stringify(checkData))
                layer.prompt({
                    formType: 1
                    , title: '敏感操作，请验证口令'
                }, function (value, index) {
                    layer.close(index);

                    layer.confirm('确定删除吗？', function (index) {
                        $.ajax({
                            url: layui.setter.hostAddr + `/portal/user/user`,
                            dataType: 'json',
                            data: JSON.stringify(delobjs),
                            async: false,
                            beforeSend: function (XMLHttpRequest) {
                                XMLHttpRequest.setRequestHeader("Authorization", layui.data('layuiAdmin').Authorization);
                                XMLHttpRequest.setRequestHeader("Content-Type", "application/json");

                            },
                            type: 'DELETE',
                            success: function (res) {
                                // console.log("删除结果====" + JSON.stringify(res))
                                doSuccess()
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                //通常情况下textStatus和errorThrown只有其中一个包含信息
                                console.log(textStatus);   //调用本次ajax请求时传递的options参数
                                console.log(errorThrown);   //调用本次ajax请求时传递的options参数
                                doFail()
                            }

                        })
                        table.reload('LAY-user-manage');
                        layer.msg('已删除');
                    });
                });
            }
            , add: function () {
                admin.popup({
                    title: '添加用户'
                    , area: ['750px', '600px']
                    , id: 'LAY-popup-user-add'
                    , success: function (layero, index) {
                        view(this.id).render('user/user/userform').done(function () {
                            form.render(null, 'layuiadmin-form-useradmin');

                            //监听提交
                            form.on('submit(LAY-user-front-submit)', function (data) {
                                // form.on('submit(*)', function(data){
                                var addfield = data.field; //获取提交的字段
                                var addUserField = {"roleIds": []}
                                for (var item in addfield) {
                                    if (addfield[item] == 'on') {
                                        addUserField['roleIds'].push(item)
                                    } else {
                                        addUserField[item] = addfield[item]
                                    }
                                }
                                addUserField['password'] = null
                                console.log("添加用户的数据===" + JSON.stringify(addUserField))
                                //提交 Ajax 成功后，关闭当前弹层并重载表格
                                $.ajax({
                                    url: layui.setter.hostAddr + "/portal/user/user",
                                    dataType: "json",
                                    contentType: "application/json",
                                    data: JSON.stringify(addUserField),
                                    async: false,
                                    beforeSend: function (XMLHttpRequest) {
                                        XMLHttpRequest.setRequestHeader("Authorization", layui.data('layuiAdmin').Authorization);
                                    },
                                    type: 'POST',
                                    success: function (res) {
                                        doSuccess()
                                    },
                                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                                        //通常情况下textStatus和errorThrown只有其中一个包含信息
                                        console.log(textStatus);   //调用本次ajax请求时传递的options参数
                                        console.log(errorThrown);   //调用本次ajax请求时传递的options参数
                                        doFail()
                                    }
                                })
                                table.reload('LAY-user-manage'); //重载表格
                                layer.close(index); //执行关闭
                            });
                        });
                    }
                });
            }
            , search: function () {
                var userVal = $("input[name='userinfo']").val()
                console.log(userVal)

                //执行重载
                table.reload('LAY-user-manage', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: {
                        keyword: userVal
                    }
                });
            }
        };

        $('.layui-btn.layuiadmin-btn-useradmin').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

    })

</script>